package com.pestano.aula2;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Listar extends ListActivity{
	
	private ListView listView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

//		listView = (ListView) findViewById(R.id.listView1);
		
//		setContentView(listView); //descomentar para usar um layout alternativo e extender de activity
		List<Map<String,String>> lista = new ArrayList<Map<String,String>>();
		
		StringBuilder urlBuilder = new StringBuilder(80);
		urlBuilder.append("http://192.168.6.200/listar_produtos.php");
		try {
			URL url = new URL(urlBuilder.toString());
			URLConnection conn = url.openConnection();
			BufferedReader bf = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));

			String result;
			while((result = bf.readLine()) != null){
				String[] row = result.split("[|]");
				Map<String,String> m = new HashMap<String, String>();
				m.put("id", row[0]);
				m.put("produto", row[1]);
				m.put("marca", row[2]);
				lista.add(m);
			}
 
		 
		}catch (Exception e) {
			Toast.makeText(getBaseContext(), "ERRO:"+e.getMessage(), Toast.LENGTH_LONG);
			return;
		}
		String[] from = {"id","produto","marca"};
		
		int[] to = {R.id.textView1,R.id.textView2,R.id.textView3}; 
		

		SimpleAdapter sa = new SimpleAdapter(getBaseContext(), lista, R.layout.listar, from, to);
		setListAdapter(sa);
	}

	@SuppressWarnings("rawtypes")
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		 
		 Intent it = new Intent(getBaseContext(), Edit.class);
		 Map value = (Map)l.getAdapter().getItem(position);
		 it.putExtra("codigo", (value.get("id").toString()));
		 startActivity(it);
		 
	}
	
	

}
